package com.dc.wifi.main.utils;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;

public class WifiScannerUtil {

    private Context context;
    private WifiManager wifiManager;
    private Gson gson;

    public WifiScannerUtil(Context context) {
        this.context = context;
        this.wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        this.gson = new Gson();
    }

    public List<ScanResult> scanWifiNetworks() {
        // 确保在主线程调用，因为需要权限请求
        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new IllegalStateException("scanWifiNetworks must be called from the main thread.");
        }

        // 检查权限
        if (!hasLocationPermission()) {
            throw new SecurityException("Location permission is required for scanning WiFi networks.");
        }

        // 扫描WiFi网络
        wifiManager.startScan();

        // 使用CountDownLatch等待扫描结果
        final CountDownLatch latch = new CountDownLatch(1);
        final List<ScanResult> results = wifiManager.getScanResults();
//        wifiManager.registerScanResultsListener(new WifiManager.ScanResultsListener() {
//            @Override
//            public void onScanResultsAvailable() {
//                results.clear();
//                results.addAll(wifiManager.getScanResults());
//                latch.countDown();
//            }
//        });

        wifiManager.registerScanResultsCallback(new Executor() {
            @Override
            public void execute(Runnable command) {
                command.run();
            }
        }, new WifiManager.ScanResultsCallback() {
            @Override
            public void onScanResultsAvailable() {
                results.clear();
                results.addAll(wifiManager.getScanResults());
                latch.countDown();
            }
        });



        try {
            // 等待扫描结果
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 将扫描结果转换为JSON
        return results;
    }

    private boolean hasLocationPermission() {
        return context.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
                == android.content.pm.PackageManager.PERMISSION_GRANTED;
    }
}